import React, {useMemo} from "react";
import {Button, Collapse, Form, Space} from "antd";
import {FormInstance} from "antd/lib/form/hooks/useForm";
import HFormItem, {HFormItemInnerProps} from "@/components/ant-ext/HFormItem";
import {ClearOutlined, SearchOutlined} from "@ant-design/icons";


export type HTableFormProps = {
    onFinish?: () => void;
    onReset?: () => void;
    name?: string;
    form?: FormInstance;
    loading?: boolean;
    item?: ({ name: string, label?: string, dynamic?: boolean, hidden?: boolean, onChange?: (val: any) => void, children?: React.ReactNode } & HFormItemInnerProps) [];
}


export default function HTableForm(props: HTableFormProps) {
    const {showQuery, hiddenQuery} = useMemo(() => {
        if (props?.form && props?.item && props.item.length > 0) {
            const showQuery: React.ReactNode[] = [];
            const hiddenQuery: React.ReactNode[] = [];
            for (let i in props.item) {
                const {hidden, dynamic, onChange} = props.item[i];
                (hidden ? hiddenQuery : showQuery).push(<HFormItem {...props.item[i]} key={i} onChange={(val: any) => {
                    onChange?.(val)
                    if (dynamic) {
                        props.form?.submit()
                    }
                }} hidden={false}/>)

            }
            return {
                showQuery, hiddenQuery: hiddenQuery.length === 0 ? <></> :
                    <Collapse defaultActiveKey={[]}>
                        <Collapse.Panel header="更多查询选项" key="1">
                            <Space>
                                {hiddenQuery}
                            </Space>
                        </Collapse.Panel>
                    </Collapse>
            }
        } else {
            return {showQuery: <></>, hiddenQuery: <></>}
        }
    }, [props.form, props.item])
    return <>
        <Form className={'tableSearchForm'} form={props.form} name={props.name}
              onFinish={props.onFinish}
              onReset={props.onReset}
        >
            <Space wrap>
                {showQuery}
                {hiddenQuery}
                <Button icon={<SearchOutlined/>} loading={props.loading} title={"查询"}
                        htmlType={"submit"}>查询</Button>
                <Button icon={<ClearOutlined/>} title={"重置"} loading={props.loading} htmlType={"reset"}>重置</Button>
            </Space>

        </Form>
    </>

}
